package com.moneywelcome.orderassembly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moneywelcome.exceptions.MwcArgsException;
import com.moneywelcome.orderassembly.model.GoldReply;
import com.moneywelcome.orderassembly.mapper.GoldReplyMapper;
import com.moneywelcome.orderassembly.service.GoldCommentService;
import com.moneywelcome.orderassembly.service.GoldReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moneywelcome.orderfacade.dto.ReplyDto;
import com.moneywelcome.orderfacade.vo.ReplyVo;
import com.moneywelcome.results.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 回复表 服务实现类
 * </p>
 *
 * @author alice
 * @since 2022-01-10
 */
@Service
public class GoldReplyServiceImpl extends ServiceImpl<GoldReplyMapper, GoldReply> implements GoldReplyService {
    @Autowired
    private GoldCommentService gcs;
    @Override
    public Map<Integer, List<ReplyDto>> loadReply(List<Integer> commentIds) {
        List<GoldReply> replys = list(new QueryWrapper<GoldReply>().in("comment_id", commentIds));
        Map<Integer, ReplyDto> replyDtoMap = new HashMap<>();
        for (GoldReply reply : replys) {
            ReplyDto replyDto = BeanUtil.copyProperties(reply, ReplyDto.class);
            replyDtoMap.put(replyDto.getReplyId(),replyDto);
        }
        for (ReplyDto value : replyDtoMap.values()) {
            ReplyDto mp = replyDtoMap.get(value.getReplyParentId());
            if(mp!=null){
                if (mp.getChildren()==null) mp.setChildren(new ArrayList<ReplyDto>());
                mp.getChildren().add(value);
            }
        }
        List<ReplyDto> replyDtos = replyDtoMap.values()
                .stream().filter(replyDto -> (replyDto.getChildren() != null || replyDto.getReplyParentId() == 0)
                        && !replyDtoMap.containsKey(replyDto.getReplyParentId()))
                .collect(Collectors.toList());
        Map<Integer, List<ReplyDto>> map = CollStreamUtil.groupByKey(replyDtos, ReplyDto::getCommentId);
        return map;
    }

    @Override
    public ReplyDto create(ReplyVo replyVo) {
        GoldReply reply = BeanUtil.copyProperties(replyVo, GoldReply.class);
        reply.setReplyTime(DateUtil.now());
        if (!save(reply)) throw new MwcArgsException("发表回复失败", StatusCode.Error);
        //增加评论热度
        gcs.levelUp(reply.getCommentId());
        return BeanUtil.copyProperties(reply,ReplyDto.class);
    }
}
